
var layer = layui.layer //弹层
    ,table = layui.table //表格
    ,form = layui.form, operationList = [], $ = layui.jquery,laydate = layui.laydate,
    customerName = getQueryVariable("customerName"), isAdmin = false,
    isApprovalParent = false, isApprovalChild = false, isOrderInquiryTab = false;

lay('.starttime').each(function(){
    laydate.render({
        elem: this
    });
});


function getAllJson(jsons) {
    let tmpitem=[]
    if(isEmpty(customerName)){
        for (let item of jsons) {
            let tmparr={}
            tmparr["value"]=item["code"];
            tmparr["name"]=item["name"];
            if (item["code"] === user.code) {
                tmparr["selected"] = true;
            }
            if(item["users"]){
                for(let it of item["users"]){
                    item["list"].push(it)
                }
            }
            if(item["list"] && item["list"].length){
                tmparr["children"]=   this.getAllJson(item["list"]);
                tmpitem.push(tmparr)
            }else{
                tmpitem.push(tmparr)
            }

        }
    }else {
        for (let item of jsons) {
            let tmparr={}
            tmparr["value"]=item["code"];
            tmparr["name"]=item["name"];
            tmparr["selected"]=true;
            if(item["users"]){
                for(let it of item["users"]){
                    item["list"].push(it)
                }
            }
            if(item["list"] && item["list"].length){
                tmparr["children"]=   this.getAllJson(item["list"]);
                tmpitem.push(tmparr)
            }else{
                tmpitem.push(tmparr)
            }

        }
    }

    return tmpitem
}

function getxmselect(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: 'auto',
        data: data,
        on: function ({ arr, change, isAdd }) {
            return this
        }
    })
}


let isMsn="否";

//订单操作标签 有该标签:false 无该标签:true
isOrderInquiryTab = getAllRolesByCurr("OrderInquiryTab");

layui.use(['dropdown'], function () {
    var dropdown = layui.dropdown;
    dropdown.onFilter("printfn", function (event) {
        var checkStatus = table.checkStatus("exporttableid");
        $.ajax({
            url: 'exportContract/getImgLogoUrl?id='+checkStatus.data[0].id,
            type: 'GET',
            async: false, // 同步
            success: function (date) {

            },
        });
        switch (event) {
            case "exportReportDomestic":
                if(checkStatus.data.length > 1){
                    layer.msg( "每次只能打印一个外销单据! ");
                    break;
                }
                if(checkStatus.data.length == 0){
                    layer.msg("请选择要打印的外销单据! ");
                    break;
                }
                window.open("views/jsp/report.jsp?ym=exportReportDomestic&code=code:"+checkStatus.data[0].id)
                break
            case "exportReport":
                $.ajax({
                    url: 'exportContract/numberParseToEnglish?id='+checkStatus.data[0].id,
                    type: 'GET',
                    async: false, // 同步
                    success: function (date) {},
                });

                if(checkStatus.data.length > 1){
                    layer.msg( "每次只能打印一个外销单据! ");
                    break;
                }
                if(checkStatus.data.length == 0){
                    layer.msg("请选择要打印的外销单据! ");
                    break;
                }
                window.open("views/jsp/report.jsp?ym=exportReport&code=code:"+checkStatus.data[0].id)
                break
            case "purchaseRequestReport_old":
                if(checkStatus.data.length > 1){
                    layer.msg( "每次只能打印一个外销单据! ");
                    break;
                }
                if(checkStatus.data.length == 0){
                    layer.msg("请选择要打印的外销单据! ");
                    break;
                }

                window.open("views/jsp/report.jsp?ym=purchaseRequestReport_old&code=code:"+checkStatus.data[0].id)
                break
            case "purchaseRequestReport_new":
                if(checkStatus.data.length > 1){
                    layer.msg( "每次只能打印一个外销单据! ");
                    break;
                }
                if(checkStatus.data.length == 0){
                    layer.msg("请选择要打印的外销单据! ");
                    break;
                }

                window.open("views/jsp/report.jsp?ym=purchaseRequestReport_new&code=code:"+checkStatus.data[0].id)
                break
        }
    });
})

layui.use(['dropdown'], function () {
    let dropdown = layui.dropdown;

    let optionData = [
        {txt: '合同资金情况表', event:'s1'},
        {txt: '外销合同产品列表', event:'s2'},
        {txt: '外销合同列表统计', event:'s3'},
        {txt: '客户订单第一次记录', event:'s4'},
        {txt: '外销产品交期一览表', event:'s5'},
        {txt: '客户订单总表', event:'contractCustomerInfo'},
        {txt: '外销费用统计', event:'s6'}
    ]

    if(!isOrderInquiryTab){
        //无查看权限 制空
        optionData = [];
    }

    dropdown.suite("#exportBtn", {
        showBy:"hover",
        align:"left",
        menus: optionData
    });

    dropdown.onFilter("contractStatistics", function (event) {
        switch (event) {
            case "s1":
                parent.intab("views/jsp/ExportBusiness/tpl/contractStatistics1.jsp","外销合同资金情况列表")
                break
            case "s2":
                parent.intab("views/jsp/ExportBusiness/tpl/contractStatistics2.jsp","外销合同产品列表")
                break
            case "s3":
                parent.intab("views/jsp/ExportBusiness/tpl/contractStatistics3.jsp","外销合同列表统计")
                break
            case "s4":
                parent.intab("views/jsp/ExportBusiness/tpl/contractStatistics4.jsp","客户订单第一次记录")
                break
            case "s5":
                parent.intab("views/jsp/ExportBusiness/tpl/contractStatistics5.jsp","外销产品交期一览表")
                break
            case "contractCustomerInfo":
                parent.intab("views/jsp/ExportBusiness/tpl/contractCustomerStatistics.jsp","客户订单总表")
                break
            case "s6":
                parent.intab("views/jsp/ExportBusiness/tpl/exportExpensesStatistics.jsp","外销费用统计")
                break
        }
    });
})

//判断当前登录用户是否为 营销部门的总监 角色 true:是 false 否
let isMarketingDirector = false;

//判断当前登录用户是否为 营销部门的总监 角色
function is_marketing_director() {
    $.ajax({
        url: 'customer/isMarketingDirector',
        async: false,
        success: function (da) {
            if (da.status == 200) {
                isMarketingDirector = da.data;
            }
        }
    });
}

//判断当前用户是否为管理员 角色 true:是 false 否
function getIsAdmin() {
    $.ajax({
        url: 'customer/isAdmin',
        async: false,
        success: function (da) {
            if (da.status == 200) {
                isAdmin = da.data;
            }
        }
    });
}
let operationNoList = [];
let salesmanCodeList = [];
let deptOperationList=[];
let deptSalesmanList=[];
layer.ready(function () {
    let departmentCode = user.departmentCode;
    if(departmentCode === "GNSYB"){
        //国内事业部
        isApprovalParent = true;
    }else if(departmentCode === "NM001" || departmentCode === "NM002"){
        //内贸一组、内贸二组
        isApprovalChild = true;
    }
    //判断当前登录用户是否为 营销部门的总监 角色 true:是 false 否
    is_marketing_director();

    //判断当前用户是否为管理员
    getIsAdmin();

    //获取当前用户的部门及人员结构树
    let treeList = getCurrentDepartmentUser();
    let userTree = [];
    if(treeList && treeList.list){
        userTree = getAllJson(treeList.list);
    }else {
        userTree = getAllJson([{name: user.name, code: user.code}]);
    }
    operationNoList = getxmselect("#operationCode","operationCode", userTree);
    salesmanCodeList = getxmselect("#salesmanCode","salesmanCode", userTree);


    //获取当前用户所属部门树()
    let currentDeptTreeList = getAllUserDepartmentTree();
    if (currentDeptTreeList && currentDeptTreeList.list) {
        let deptTree = getAllJson(currentDeptTreeList.list);
        deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", deptTree);
        deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", deptTree);
    } else {
        deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", [{name: user.name, value: user.code}]);
        deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", [{name: user.name, value: user.code}]);
    }

    //获取币种
    $.ajax({
        url:"receivePayment/getCurrencyInfo",
        success:function(data){
            if(data.status == 200){
                for(let i in data.data){
                    $('#currencyCode').append(new Option(data.data[i].name, data.data[i].code));
                }
                form.render('select');
            }
        }
    });
    //获取所有公司信息
    $.ajax({
        url:"receivePayment/getCompanyInfo",
        success:function(data){
            if(data.status == 200){
                for(let i in data.data){
                    //公司名称
                    $('#signingCompanyCode').append(new Option(data.data[i].name, data.data[i].code));
                }
                form.render('select');
            }
        }
    });
    $.ajax({
        url: 'billChange/isMsn',
        type: 'GET',
        async: false, // 同步
        success: function (date) {
            isMsn=date.data
        }
    })

    let searchURL = window.location.search;
    searchURL = searchURL.substring(1, searchURL.length);
    let type = searchURL.split("&")[0].split("=")[1];
    let operationCodes = operationNoList.getValue("value").join();
    let salesmanCodes = salesmanCodeList.getValue("value").join();
    if(user.code === "admin"){
        operationCodes = "admin";
        salesmanCodes = "admin";
    }
    let obj = {operationCode : operationCodes, salesmanCode : salesmanCodes};
    if(!isEmpty(type) && type == "statistics"){
        //来源于控制台统计

        //获取当月开始日期
        let time = new Date();
        let month = ("0" + (time.getMonth() + 1)).slice(-2);
        let year = time.getFullYear();
        //获取当月第一天
        let startDay = new Date(year, month, 1);
        let startCurryDay = startDay.getDate();
        startCurryDay = startCurryDay < 10 ? '0' + startCurryDay : startCurryDay;
        let startDate = time.getFullYear() + "-" + (month) + "-" + (startCurryDay);
        //签约日期
        laydate.render({
            elem: '#signingDateStart',
            value: startDate,
            isInitValue: true
        });

        //获取当月结束日期
        let endDay = new Date(year, month, 0);
        let endCurryDay = endDay.getDate();
        endCurryDay = endCurryDay < 10 ? '0' + endCurryDay : endCurryDay;
        let endDate = time.getFullYear() + "-" + (month) + "-" + (endCurryDay);
        //签约日期
        laydate.render({
            elem: '#signingDateEnd',
            value: endDate,
            isInitValue: true
        });

        obj = {operationCode : user.code, signingDateStart : startDate, signingDateEnd : endDate, statusList : "1,2,3,4,6"}
    }
    if(!isEmpty(customerName)){
        let name = decodeURI(customerName);
        $("#billNo").val(name);
        obj = {operationCode : operationCodes, salesmanCode : salesmanCodes, billNo : name};
    }

    initTable(obj);
});



form.render();//表单刷新
function initTable(obj){
    table.render({
        elem: '#exportselect'
        ,where:obj
        ,url:'exportContract/getListByPage'
        ,toolbar: '#exporttoolbar'
        ,totalRow: true
        ,cols: [[
            {checkbox: true, fixed: true}
            ,{field: 'numbers',width: 50,type:'numbers',title:'序号', totalRowText: '合计'}
            ,{field:'statusStr', title:'单据类型', width: 120}
            ,{field:'signingDate', title:'签约日期',sort:true,width: 120}
            ,{field:'salesmanName', title:'业务员',sort:true,width: 120}
            ,{field:'billNo', title:'合同编号',sort:true,width: 220,event: "contractno"}
            ,{field:'customerContactNo', title:'客户合同号',sort:true,width: 120}
            ,{field:'customerName', title:'客户名称',sort:true,width: 120}
            ,{field:'customerCode', title:'客户编码',sort:true,width: 120}
            ,{field:'currency', title:'币种',sort:true,width: 120}
            ,{field:'totalContractAmount', title:'合同总额',sort:true,width: 120, totalRow: true}
            ,{field:'priceTermsName', title:'价格术语',sort:true,width: 120}
            ,{field:'businessModelName', title:'业务模式',sort:true,width: 120}
            ,{field:'isDeclare', title:'是否报关',sort:true,width: 120,templet: function(data){
                    if(0 == data.isDeclare){
                        return "否";
                    }else {
                        return "是";
                    }
                }}
            ,{field:'advancePaymentAmount', title:'预收款金额',sort:true,width: 120, totalRow: true}
            ,{field:'customerAccountingPeriod', title:'客户账期',sort:true,width: 120}
            ,{field:'signingCompanyName', title:'签约公司',sort:true,width: 220}
            ,{field:'usdRate', title:'美元汇率',sort:true,width: 120}
            ,{field:'rmbRate', title:'人民币汇率',sort:true,width: 120}
            ,{field:'carryTime', title:'出运日期',sort:true,width: 120}
            ,{field:'transitPlaceName', title:'起运地',sort:true,width: 120}
            ,{field:'destinationName', title:'目的地',sort:true,width: 120}
            ,{field:'paymentTerm', title:'付款期限',sort:true,width: 120}
            ,{field:'rechargeOccupancy', title:'充值占用',sort:true,width: 120,templet: function(data){
                    if(0 == data.rechargeOccupancy){
                        return "否";
                    }else {
                        return "是";
                    }
                }}
            ,{field:'customerComplaintNo', title:'客诉单号',sort:true,width: 120}
            ,{field:'operator', title:'操作员',sort:true,width: 120}
            ,{field:'whetherToReplenish', title:'是否补货',sort:true,width: 120,templet: function(data){
                    if(0 == data.whetherToReplenish){
                        return "否";
                    }else {
                        return "是";
                    }
                }}
            ,{field:'memo', title:'备注', width: 220}
            // ,{fixed: 'right', width:240, toolbar: '#exporteditor', title:'操作'}
            ,{fixed: 'right', width:280, title:'操作',templet: function(d){
                    // 单据状态/类型（1：草稿箱，2：待批箱，3：已批箱，4：完成箱，5垃圾箱，6终止箱）
                    if(isOrderInquiryTab){
                        if(isMsn=="是" && !isApprovalParent && !isApprovalChild){//管理员
                            var html="<div>"
                            if(d.status==1 || d.status==2|| d.status==3){
                                html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"update\">修改</a>";
                            }
                            if(d.status==1){
                                html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"submits\">提交审批</a>" +
                                    "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"delect\">删除</a>"
                            }
                            if(d.status==2 && !(isApprovalChild || d.deptCode === "GNSYB")){
                                html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"through\">审批通过</a>"
                            }
                            if(d.status==2 || d.status==3){
                                html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"backtothe\">审批退回</a>"
                            }
                            if(d.status==3){
                                html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"complete\">完成</a>"
                            }
                            if(d.status==3 && (isMarketingDirector || isAdmin)){
                                html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"termination\">终止</a>"
                            }
                            if(d.status==5){
                                html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"delect\">彻底删除</a>"
                            }
                            if(d.status==6 && (isMarketingDirector || isAdmin)){
                                html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"terminationBack\">取消终止</a>"
                            }
                            return html+"</div>";
                        }else if(isMsn=="是" && (isApprovalParent || isApprovalChild)){
                            var html="<div>"
                            if(d.status==21 && isApprovalChild){
                                html=html+"<a style='background-color:red;' class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"xxx\">等待上级审批</a>";
                            }
                            if(d.status==1 || d.status==2|| d.status==3){
                                html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"update\">修改</a>";
                            }
                            if(d.status==1){
                                html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"submits\">提交审批</a>" +
                                    "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"delect\">删除</a>"
                            }
                            if(d.status==2 && isApprovalChild){
                                html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"through\">审批通过</a>"
                            }
                            if(d.status==2 && d.deptCode === "GNSYB" && isApprovalParent){
                                html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"through\">审批通过</a>"
                            }
                            if(d.status==21 && isApprovalParent){
                                html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"through\">审批通过</a>"
                            }
                            if(d.status==2 || (d.status==21 && isApprovalChild)){
                                html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"backtothe\">审批退回</a>"
                            }
                            if((d.status==21 && isApprovalParent) || (d.status==3 && isApprovalParent)){
                                html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"backtothe\">审批退回</a>"
                            }
                            if(d.status==3){
                                html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"complete\">完成</a>"
                            }
                            if(d.status==3 && (isMarketingDirector || isAdmin)){
                                html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"termination\">终止</a>"
                            }
                            if(d.status==5){
                                html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"delect\">彻底删除</a>"
                            }
                            if(d.status==6 && (isMarketingDirector || isAdmin)){
                                html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"terminationBack\">取消终止</a>"
                            }
                            return html+"</div>";
                        }else {
                            var html = "<div>"
                            if(d.status==2 || d.status==21){
                                html=html+"<a style='background-color:red;' class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"xxx\">等待上级审批</a>";
                            }
                            if (d.status == 1) {
                                html = html + "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"update\">修改</a>" +
                                    "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"submits\">提交审批</a>" +
                                    "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"delect\">删除</a>"
                            }
                            if (d.status == 2) {
                                html = html + "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"backtothe\">审批退回</a>"
                            }
                            if(d.status==3){
                                html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"complete\">完成</a>"
                            }
                            if(d.status==3 && (isMarketingDirector || isAdmin)){
                                html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"termination\">终止</a>"
                            }
                            if(d.status==5){
                                html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"delect\">彻底删除</a>"
                            }
                            if(d.status==6 && (isMarketingDirector || isAdmin)){
                                html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"terminationBack\">取消终止</a>"
                            }
                            return html + "</div>";
                        }
                    }else {
                        let html = "<div>"
                        return html + "</div>";
                    }
                }}
        ]]
        ,id: 'exporttableid'
        ,height: $(document).height() - $('#exportselect').offset().top - 50
        ,page: true
        ,limit: 50
        ,limits: [50, 100, 200, 300, 500]
        ,done: function (res, curr, count) {
            //字段权限控制
            if(!isOrderInquiryTab){
                $("[data-field='totalContractAmount']").css('display','none');
            }
        }
    });
}

table.on('tool(exporttable)', function(obj){
    let data = obj.data;
    let id = data.id;
    let billNo = data.billNo;
    if(obj.event === 'update') {
        parent.intab("views/jsp/ExportBusiness/tpl/updateExport.jsp?id="+id,"修改外销")
        //校验数据是否被调用
        /*$.ajax({
            url: "exportContract/checkIsCanModified?id=" + id + "&billNo=" + billNo,
            async: false,
            success: function (res) {
                if (res.status == 200) {
                    //1:采购调用 2:出运计划调用 0:未被调用
                    if (0 === res.data) {
                        parent.intab("views/jsp/ExportBusiness/tpl/updateExport.jsp?id=" + id, "修改外销")
                    } else if (1 === res.data) {
                        layer.msg("已做采购，无法修改", {icon: 5});
                    } else if (2 === res.data) {
                        layer.msg("已做出运计划，无法修改", {icon: 5});
                    }

                } else {
                    layer.msg(res.msg, {icon: 5});
                }
            }
        });*/
    }else if(obj.event === 'delect'){
        layer.confirm('确认删除？',confirmInfo(3,6), function (index) {
            layer.close(index);
            let dataBases={
                id:id,
                status:data.status
            }
            $.ajax({
                type:"POST",
                dataType:"json",
                contentType: 'application/json',
                data:JSON.stringify(dataBases),
                url:"exportContract/delete",
                success:function(res){
                    if(res.status == 200){
                        layer.msg("删除成功", {icon: 6});
                        table.reload('exporttableid', {
                            page: {
                                curr: 1 //重新从第 1 页开始
                            }
                            ,where: data.field
                        }, 'data');
                        return false;
                    }else {
                        layer.msg(res.msg, {icon: 5});
                    }
                }
            });
        });
    }else if(obj.event === 'submits'){
        layer.confirm('确定提交审批吗', confirmInfo(3, 5), function (index) {
            // startPurchaseProcess(id);
            operationData(data, 1, "提交审批");
        });
    }else if(obj.event === 'through'){
        layer.confirm('确定审批通过吗', confirmInfo(3, 5), function (index) {
            operationData(data, 2, "审批通过");
        });
    }else if(obj.event === 'backtothe'){
        //校验数据是否被调用
        $.ajax({
            url: "exportContract/getUsedInfoByConcatNo?id=" + id + "&billNo=" + billNo,
            async: false,
            success: function (res) {
                if (res.status == 200) {
                    //1:采购调用 2:出运计划调用 0:未被调用
                    if (0 === res.data) {
                        layer.confirm('确定审批退回吗', confirmInfo(3, 5), function (index) {
                            operationData(data, 3, "审批退回");
                        });
                    } else if (1 === res.data) {
                        layer.msg("已做采购，无法审批退回", {icon: 5});
                    } else if (2 === res.data) {
                        layer.msg("已做出运计划，无法审批退回", {icon: 5});
                    }

                } else {
                    layer.msg(res.msg, {icon: 5});
                }
            }
        });
    }else if(obj.event === 'termination'){
        layer.confirm('确定终止吗', confirmInfo(3, 5), function (index) {
            operationData(data, 6, "终止");
        });
    }else if(obj.event === 'terminationBack'){
        layer.confirm('确定取消终止吗', confirmInfo(3, 5), function (index) {
            operationData(data, 7, "取消终止");
        });
    }else if(obj.event === 'complete'){
        layer.confirm('确定完成吗', confirmInfo(3, 5), function (index) {
            operationData(data, 4, "完成");
        });
    }else if(obj.event === 'reduction'){
        layer.confirm('确定还原吗', confirmInfo(3, 5), function (index) {
            operationData(data, 5, "还原");
        });
    }else if (obj.event === "contractno"){
        parent.intab("views/jsp/ExportBusiness/tpl/viewexport.jsp?id="+obj.data.id,"外销明细")
    }
});

//审批流开始，获取流程ID
function startPurchaseProcess(bid) {
    let res;
    $.ajax({
        type : 'get',
        data:{"processDefId":'export',"bid":bid,"variables":null},
        url:'process/startProcess',
        dataType:"json",
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        async:false,
        success : function (da) {
            if(da.status==200 ){
                res=da.data;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return res;
}

function operationData(data, operation, msg){
    let fields = {
        id : data.id,
        billNo : data.billNo,
        operation: operation
    }
    $.ajax({
        type:"POST",
        dataType:"json",
        contentType: 'application/json',
        data:JSON.stringify(fields),
        url:"exportContract/operation",
        success:function(res){
            if(res.status == 200){
                layer.msg(msg, {icon: 6});
                table.reload('exporttableid', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    ,where: data.field
                }, 'data');
                return false;
            }else {
                layer.msg(res.msg, {icon: 5});
            }
        }
    });
}

function getCodeList(){
    let userCode = "";
    for(let i in operationList){
        if(isEmpty(userCode)){
            userCode = userCode + operationList[i].code;
        }else{
            userCode = userCode + "," + operationList[i].code;
        }
    }
    return userCode;
}

form.on('submit(submitform)', function(data){
    initTable(data.field);
    return false;
});

table.on('toolbar(exporttable)', function(obj){
    let checkStatus = table.checkStatus(obj.config.id);
    switch(obj.event){
        case 'news':
            parent.intab("views/jsp/ExportBusiness/tpl/newupexport.jsp","新增外销")
            break;
        case 'copys':
            let data = checkStatus.data;
            if(data.length == 1){
                parent.intab("views/jsp/ExportBusiness/tpl/copyExport.jsp?id="+data[0].id,"复制外销合同");
            }else{
                layer.msg("复制合同请选取一个数据进行操作")
            }
            break;
        case 'checkSubmit':
            batchOperation(checkStatus.data, "一键提交成功！", 1);
            break;
        case 'checkAdopt':
            batchOperation(checkStatus.data, "一键通过成功！", 2);
            break;
        case 'salesmanUpdate':
            salesmanUpdateOperation(checkStatus.data);
            break;
    };
});

let updateSalesmanData = [];

function salesmanUpdateOperation(data) {
    if(data.length == 0){
        layer.msg("请选择数据！", {icon: 5});
        return;
    }
    updateSalesmanData = data;

    getSelectInfoOfSalesman();

    return layer.open({
        type: 1,
        title: "转移单据",
        area: ['800px', '700px'],
        content: $("#salesmanUpdateWindow")
    });
}

//监听转移提交
form.on('submit(shareSubmit)', function(data){
    if(isEmpty(data.field["salesmanCodeUpdate"])){
        layer.msg("请选择业务员！", {icon: 5});
        return  false;
    }
    //修改选中单据得业务员
    let fields = {};
    fields["operationReqs"] = updateSalesmanData;
    fields["salesmanCodeUpdate"] = data.field["salesmanCodeUpdate"];
    fields["salesmanNameUpdate"] = $("#salesmanNameUpdate").val();
    $.ajax({
        type:"POST",
        dataType:"json",
        contentType: 'application/json',
        data:JSON.stringify(fields),
        url:"exportContract/batchUpdateSalesman",
        success:function(res){
            if(res.status == 200){
                layer.closeAll();
                table.reload('exporttableid', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    ,where: data.field
                    ,done(){
                        layer.msg("单据转移成功！", {icon: 6});
                    }
                }, 'data');
                return false;
            }else {
                layer.msg(res.msg, {icon: 5});
            }
        }
    });
    return false;
});

//用户组
let userRoleList = [];
function getAllJsonOfSalesman(jsons) {
    let tmpitem=[]
    for (let item of jsons) {
        let tmparr={}
        tmparr["value"]=item["code"];
        tmparr["name"]=item["name"];
        if(!isEmpty(userRoleList)){
            if(checkIsContain(userRoleList, item["code"])){
                tmparr["selected"]=true;
            }
        }
        if(item["users"]){
            for(let it of item["users"]){
                item["list"].push(it)
            }
        }
        if(item["list"] && item["list"].length){
            tmparr["children"]=   this.getAllJson(item["list"]);
            tmpitem.push(tmparr)
        }else{
            tmpitem.push(tmparr)
        }

    }
    return tmpitem
}

function getXMSelectSalesman(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        clickClose: true,       //单选完关闭下拉框
        filterable: true,       //搜索
        direction: 'down',      // 展开方向 下
        radio: true,            //单选
        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: 'auto',
        data: data,
        on: function ({ arr, change, isAdd }) {
            if(arr.length > 0){
                $("#salesmanNameUpdate").val(arr[0]["name"]);
            }
            return this
        }
    })
}

//获取所有用户所管理的部门
function getAllDepartmentUser() {
    let userTree = {};
    $.ajax({
        type: 'get',
        url: 'department/getAllDepartmentUser',
        dataType: "json",
        async: false,
        success: function (data) {
            if (data.status == 200) {
                userTree = data.data;
            }
        },
        error: function (data) {
        }
    });
    return userTree;

}

function getSelectInfoOfSalesman() {
    let userList = getAllDepartmentUser();
    if(userList && userList.list){
        let userTree = getAllJsonOfSalesman(userList.list);
        getXMSelectSalesman("#salesmanCodeUpdate","salesmanCodeUpdate", userTree)
    }else {
        getXMSelectSalesman("#salesmanCodeUpdate","salesmanCodeUpdate", [{name: user.name, value: user.code}])
    }
}

//一键操作
function batchOperation(data, msg, type){
    if(data.length == 0){
        layer.msg("请选择数据！", {icon: 5});
        return;
    }
    let fields = {};
    fields["type"] = type;
    fields["operationReqs"] = data;
    $.ajax({
        type:"POST",
        dataType:"json",
        contentType: 'application/json',
        data:JSON.stringify(fields),
        url:"exportContract/batchOperation",
        success:function(res){
            if(res.status == 200){
                layer.msg(msg, {icon: 6});
                table.reload('exporttableid', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    ,where: data.field
                }, 'data');
                return false;
            }else {
                layer.msg(res.msg, {icon: 5});
            }
        }
    });
}

$("#salestarget").on("click",function () {
    parent.intab("views/jsp/ExportBusiness/tpl/salestarget.jsp","销售目标")
});

//提示信息渲染
function confirmInfo(icon, anim) {
    let data = {
        icon: icon,
        title: "提示",
        offset: "auto",
        skin: 'layui-layer-molv',
        anim: anim
    }
    return data;
}

//字符串val是否在数据arr中(true:在 false:不在)
function checkIsContain(arr, val) {
    if(arr.indexOf(val) > -1){
        return true;
    }else {
        return false;
    }
}

//字段是否为空或者零
function isEmpty(obj){
    if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
        return true;
    }else{
        return false;
    }
}

function downLogo(url){
    $.ajax({
        url: 'ftp/onLine2?pathString='+url,
        type: 'GET',
        async: false, // 同步
        success: function (date) {

        },
        error:function (date) {

        }
    });
}

document.getElementById('clear').onclick = function(){
    operationNoList.setValue([ ]);
    salesmanCodeList.setValue([ ]);
    deptSalesmanList.setValue([ ]);
    deptOperationList.setValue([ ]);
};